package project.elements.order;

import java.util.ArrayList;
import java.util.List;

import project.elements.base.Job;
import project.elements.priority.PriorityCalculator;

public class BubbleSort extends OrderStrategy {

	public static final String TYPE = "BUBBLE";
	private static final BubbleSort SINGLETON = new BubbleSort();

	private BubbleSort() {
		super();
	}

	public static BubbleSort singleton() {
		return SINGLETON;
	}

	@Override
	public String getType() {
		return TYPE;
	}

	@Override
	public ArrayList<Job> orderJobs(List<Job> jobs, PriorityCalculator priorityCalculator) {
		ArrayList<Job> listToSort = null;
		if (jobs instanceof ArrayList) {
			listToSort = (ArrayList<Job>) jobs;
		} else {
			listToSort = new ArrayList<Job>(jobs);
		}
		for (int i = listToSort.size(); i >= 2; i--) {
			for (int j = 0; j < i - 1; j++) {
				replaceByPriority(listToSort, j, priorityCalculator);
			}
		}
		// System.out.println(listToSort);
		return listToSort;
	}

	private static void replaceByPriority(ArrayList<Job> listToSort, int j, PriorityCalculator priorityCalculator) {
		Job elementAtJ = listToSort.get(j);
		Job elementAtJPlus = listToSort.get(j + 1);
		if (PriorityCalculator.compareJobs(priorityCalculator, elementAtJ, elementAtJPlus) == -1) {
			listToSort.set(j, elementAtJPlus);
			listToSort.set(j + 1, elementAtJ);
		}
	}
}
